package com.medusa.aps.business.modules.plan.model.output;

import cn.hutool.core.collection.CollUtil;
import com.medusa.aps.business.model.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.experimental.Accessors;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Data
@Accessors(chain = true)
@Schema(name = "甘特图实体对象")
public class GanttChartVo {
    /**
     * 开始时间
     */
    @Schema(description = "检索结果计划时间范围开始时间")
    private LocalDateTime planStartDate;
    /**
     * 结束时间
     */
    @Schema(description = "检索结果计划时间范围结束时间")
    private LocalDateTime planEndDate;

    /**
     * 甘特图分页查询结果
     */
    @Schema(description = "甘特图分页查询结果")
    private Page<PageListModel> ganttDatas = new Page<>();

    public GanttChartVo planDateRange() {
        List<PageListModel> records = getGanttDatas().getRecords();
        if (CollUtil.isEmpty(records)) {
            return this;
        }
        AtomicReference<LocalDateTime> planStartDateRef = new AtomicReference<>();
        AtomicReference<LocalDateTime> planEndDateRef = new AtomicReference<>();
        records.stream()
                .flatMap(pageListModel -> pageListModel.getGanttList().stream())
                .forEach(
                        ganttChart -> {
                            LocalDateTime planStartTime = ganttChart.getPlanStartTime();
                            if (planStartTime != null) {
                                LocalDateTime startDate = planStartDateRef.get();
                                if (startDate == null || startDate.isAfter(planStartTime)) {
                                    planStartDateRef.set(planStartTime);
                                }
                            }
                            LocalDateTime planEndTime = ganttChart.getPlanEndTime();
                            if (planEndTime != null) {
                                LocalDateTime endDate = planEndDateRef.get();
                                if (endDate == null || endDate.isBefore(planEndTime)) {
                                    planEndDateRef.set(planEndTime);
                                }
                            }
                        }
                );
        this.setPlanStartDate(planStartDateRef.get());
        this.setPlanEndDate(planEndDateRef.get());
        return this;
    }


}
